﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using LabNet.Core.ViewModels;
using LabNet.Server.Contract;
using LabNet.Server.Domain;

namespace LabNet.Web.Scffolding.Controllers
{
    public class UsersController : Controller
    {
        protected IUserService UserService;

        public UsersController(IUserService userService)
        {
            UserService = userService;
        }

        // GET: Users
        public async Task<ActionResult> Index()
        {
            var results = await UserService.GetAsync();
            var model = new List<GridUserModel>();
            if (results.Any())
            {
                foreach (var result in results)
                {
                    var userIems = new GridUserModel
                    {
                        Id = result.Id,
                        Name = result.Name,
                        UserName = result.UserName,
                        Email = result.Email
                    };
                    model.Add(userIems);
                }
            }
            return View(model);
        }

        // Post: Create User

        [HttpGet]
        public ActionResult Create()
        {
            var model = new CreateUserModel();
            return View(model);
        }

        [HttpPost]
        public async Task<ActionResult> Create(CreateUserModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new User();
                if (model != null)
                {
                    user.Id = new long();
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.UserName = model.UserName;
                    user.Email = model.Email;
                    user.Paswword = model.Password;
                    user.Created = DateTime.Now;
                    user.IsAdministator = false;
                    user.IsActive = true;
                }

                //UserService.InsertOrUpdate(user);
                await UserService.InsertOrUpdateAsync(user);
                return RedirectToAction("Index", "Users");
            }

            return View(model);

        }
    }
}